<template>
  <div class="app-container" v-loading="appLoading" :element-loading-text="loadingText">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="真实姓名" prop="realName">
        <el-input v-model="queryParams.realName" placeholder="真实姓名" clearable size="mini"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="手机号码" clearable size="mini"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="身份证号码" prop="idNumber">
        <el-input v-model="queryParams.idNumber" placeholder="身份证号码" clearable size="mini"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="客户状态" clearable size="mini">
          <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="+dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="queryParams.gender" placeholder="客户性别" clearable size="mini">
          <el-option v-for="dict in sexOptions" :key="dict.value" :label="dict.label" :value="+dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="创建日期">
        <el-date-picker v-model="dateRange" size="mini" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPerm="['beauty:member:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPerm="['beauty:member:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                   v-hasPerm="['beauty:member:remove']">删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange" size="mini"
              :height="tableHeight">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="客户编号" prop="id" width="200" align="center"/>
      <el-table-column label="手机号" align="center" prop="phone" width="120"/>
      <el-table-column label="绑定微信" align="center" prop="openId">
        <template slot-scope="scope">
          <span v-if="scope.row.openId== '' || scope.row.openId == undefined" style="color: red;">未绑定</span>
          <span v-else style="color: limegreen">已绑定</span>
        </template>
      </el-table-column>
      <el-table-column label="头像" align="center" prop="avatar" width="100px">
        <template slot-scope="scope">
          <span v-if="scope.row.avatar==''">暂无</span>
          <el-image v-else :src="scope.row.avatar" style="width: 40px; height: 40px" fit="fill"
                    :preview-src-list="[scope.row.avatar]"/>
        </template>
      </el-table-column>
      <el-table-column label="真实姓名" align="center" prop="realName"/>
      <el-table-column label="详细地址" align="center" width="240">
        <template slot-scope="{row}">
          <span v-if="row.county==''||row.province==''||row.county==''">暂无</span>
          <span v-else>{{ row.province + row.city + row.county + row.address }}</span>
        </template>
      </el-table-column>
      <el-table-column label="身份证号码" align="center" prop="idNumber" width="200"/>
      <el-table-column label="性别" prop="gender" align="center" :formatter="sexFormat" width="100"></el-table-column>
      <el-table-column label="当前余额" align="center" prop="amount" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.amount }} 元</span>
        </template>
      </el-table-column>
      <el-table-column label="历史充值金额" align="center" prop="historyAmount" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.historyAmount }} 元</span>
        </template>
      </el-table-column>
      <el-table-column label="获得积分" align="center" prop="point" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.point }} 积分</span>
        </template>
      </el-table-column>
      <el-table-column label="历史获得积分" align="center" prop="historyPoint" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.historyPoint }} 积分</span>
        </template>
      </el-table-column>
      <el-table-column label="创建日期" align="center" prop="gmtCreate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtCreate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch v-hasPerm="['beauty:member:edit']" v-model="scope.row.status" :active-value="0"
                     :inactive-value="1"
                     @change="handleStatusChange(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="170px">
        <template slot-scope="{row}">
          <el-dropdown class="handle-button">
            <span class="el-dropdown-link">操作<i class="el-icon-arrow-down el-icon--right"/>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="handleCashTopUp(row)">
                <el-button size="mini" type="text" icon="el-icon-coin" v-hasPerm="['beauty:member:topUp']">现金充值
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item @click.native="handleAlipayTopUp(row)">
                <el-button size="mini" type="text" icon="el-icon-coin" v-hasPerm="['beauty:member:topUp']">支付宝充值
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <router-link :to="'/member/statistics/' + row.id" class="link-type">
                  <el-button size="mini" type="text" icon="el-icon-s-finance"
                             v-hasPerm="['beauty:member:query']">统计报表
                  </el-button>
                </router-link>
              </el-dropdown-item>
              <el-dropdown-item>
                <router-link :to="'/topUp/info/' + row.id" class="link-type">
                  <el-button size="mini" type="text" icon="el-icon-info"
                             v-hasPerm="['beauty:member:topUp']">充值记录
                  </el-button>
                </router-link>
              </el-dropdown-item>
              <el-dropdown-item @click.native="handleUpdate(row)">
                <el-button size="mini" type="text" icon="el-icon-edit" v-hasPerm="['beauty:member:edit']">修改
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item @click.native="handleResetPwd(row)">
                <el-button size="mini" type="text" icon="el-icon-edit" v-hasPerm="['beauty:member:edit']">重置密码
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item @click.native="handleDelete(row)">
                <el-button size="mini" type="text" icon="el-icon-delete" v-hasPerm="['beauty:member:remove']">删除
                </el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!--分页插件-->
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.current" :limit.sync="queryParams.size"
                @pagination="getList"/>

    <!-- 添加或修改管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body class="dialog-member">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号" clearable maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.id == undefined" label="用户密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入用户密码" type="password"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="form.realName" placeholder="请输入真实姓名" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号码" prop="idNumber">
              <el-input v-model="form.idNumber" placeholder="请输入身份证号码" clearable maxlength="18" minlength="15"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户性别" prop="gender">
              <el-select v-model="form.gender" placeholder="请选择">
                <el-option v-for="dict in sexOptions" :key="dict.value" :label="dict.label"
                           :value="+dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在城市" prop="county">
              <el-cascader size="mini" :options="options" v-model="selectedOptions" @change="handleChange"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入详细地址" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in statusOptions" :key="dict.value" :label="+dict.value">{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--打开支付宝支付框-->
    <el-dialog title="请使用支付宝支付" :visible.sync="openPay" center :close-on-click-modal="false" :before-close="handleClose"
               append-to-body>
      <el-card class="ub main-center">
        <div>
          <span class="ali-pay">订单号:<span class="ali-pay-item" style="color: darkblue">{{
              payObj.orderId
            }}</span></span>
        </div>
        <div>
          <span class="ali-pay">总金额:<span class="ali-pay-item" style="color: red">{{ payObj.amount }}</span> 元</span>
        </div>
      </el-card>
      <div style="text-align:center">
        <vue-qr :text="payObj.payUrl" :size="200"/>
        <div class="ali-pay">请使用支付宝扫码</div>
      </div>
    </el-dialog>


    <!--打开充值金额-->
    <el-dialog title="在线充值" :visible.sync="openAmount" center :close-on-click-modal="false"
               append-to-body width="30%">
      <div style="text-align:center">
        <div class="ali-pay" style="color: red">注意: 1 = 1 RMB</div>
      </div>
      <el-form ref="topUpForm" :model="topUpForm" :rules="topUpAmountRules">
        <el-form-item label="充值金额" prop="topUpAmount">
          <el-input v-model="topUpForm.topUpAmount" placeholder="请输入充值金额" clearable maxlength="6" minlength="1"/>
        </el-form-item>
      </el-form>
      <div style="text-align:center">
        <div class="ali-pay">当前充值金额: {{ topUpForm.topUpAmount }} = {{ topUpForm.topUpAmount }} RMB</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTopUp">确 定</el-button>
        <el-button @click="canceTopUp">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
// 引入生成二维码的组件
import vueQr from 'vue-qr'
import {
  listMember,
  getMember,
  delMember,
  addMember,
  updateMember,
  changeMemberStatus,
  topUpWithAlipay,
  topUpWithCash,
  resetMemberPwd
} from '@a/beauty/member'
import { getTopUp } from '@a/beauty/topUp'
import { regionDataPlus, CodeToText, TextToCode } from 'element-china-area-data'

export default {
  name: 'Member',
  components: {
    vueQr
  },
  data() {
    return {
      // 默认密码
      initPassword: undefined,
      // 充值类型 0 现金 1 支付宝
      topUpType: undefined,
      // 定时轮询对象
      intervalObj: undefined,
      appLoading: false,
      loadingText: '',
      topUpForm: {},
      // 支付对象
      payObj: {},
      // 打开输入支付金额
      openAmount: false,
      // 是否打开支付宝二维码支付层
      openPay: false,
      // 市区级联
      options: regionDataPlus,
      selectedOptions: [],
      // 日期范围
      dateRange: [],
      tableHeight: window.innerHeight - 340,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 轮播图管理表格数据
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 性别状态字典
      sexOptions: [],
      // 状态(0.可用 1.不可用)字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        // 当前页
        current: 1,
        // 每页显示条数
        size: 10,
        realName: null,
        idNumber: null,
        phone: null,
        openId: null,
        email: null,
        gender: null,
        status: null
      },
      // 表单参数
      form: {},
      topUpAmountRules: {
        topUpAmount: [
          { required: true, message: '充值金额不能为空', trigger: 'blur' },
          {
            message: '充值金额格式不合法',
            trigger: 'blur',
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
          }
        ]
      },
      // 表单校验
      rules: {
        status: [
          { required: true, message: '用户状态不能为空', trigger: 'blur' }
        ],
        county: [
          { required: true, message: '所在城市不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '默认密码不能为空', trigger: 'blur' }
        ],
        realName: [
          { required: true, message: '真实姓名不能为空', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '详细地址不能为空', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '客户性别不能为空', trigger: 'blur' }
        ],
        idNumber: [
          { required: true, message: '身份证号码不能为空', trigger: 'blur' },
          {
            pattern: /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/,
            message: '请输入正确的身份证号码',
            trigger: 'blur'
          }
        ],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getDictItems('sys_user_sex').then(response => {
      this.sexOptions = response.data
    })
    this.getDictItems('sys_normal_disable').then(response => {
      this.statusOptions = response.data
    })
    this.getConfigKey('sys.user.initPassword').then(response => {
      this.initPassword = response.message
    })
  },
  methods: {
    // 现金充值
    handleCashTopUp(row) {
      this.topUpForm = {}
      this.openAmount = true
      this.topUpType = 0
      this.topUpForm.topUpMemberId = row.id
    },
    // 提交充值
    submitTopUp() {
      this.$refs['topUpForm'].validate(valid => {
        if (valid) {
          switch (this.topUpType) {
            // 现金
            case 0:
              topUpWithCash(this.topUpForm.topUpMemberId, this.topUpForm.topUpAmount).then(res => {
                this.msgNoticeSuccess('充值成功')
                this.getList()
                this.topUpType = undefined
                this.topUpForm = {}
                this.openAmount = false
              })
              break
            // 支付宝
            case 1:
              this.openAmount = false
              this.appLoading = true
              this.loadingText = '订单创建并支付宝支付中'
              setTimeout(() => {
                this.$confirm('是否确定创建订单并使用支付宝支付?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  topUpWithAlipay(this.topUpForm.topUpMemberId, this.topUpForm.topUpAmount)
                    .then(res => {
                      this.payObj = res.data
                      this.msgNoticeSuccess('订单创建成功，请扫码支付')
                      const tx = this
                      tx.openPay = true
                      tx.intervalObj = setInterval(function() {
                        // 查询日志 判断是否支付成功
                        getTopUp(tx.payObj.orderId).then(r => {
                          if (r.data.status === 1) {// 说明订单状态为支付成功
                            // 清空定时器
                            clearInterval(tx.intervalObj)
                            tx.$notify({
                              title: '支付成功',
                              message: '【' + tx.payObj.orderId + '】的订单编写支付成功',
                              type: 'success'
                            })
                            tx.openPay = false
                            tx.topUpForm = {}
                            tx.getList()
                          }
                        }).catch(() => {
                          // 清空定时器
                          clearInterval(tx.intervalObj)
                        })
                      }, 2000)
                      this.appLoading = false
                      this.topUpType = undefined
                      this.loadingText = ''
                    })
                }).catch(() => {
                  this.msgNoticeError('创建订单失败')
                  this.topUpForm = {}
                  this.topUpType = undefined
                  this.appLoading = false
                }).catch(() => {
                  this.msgNoticeError('创建已取消')
                  this.topUpType = undefined
                  this.topUpForm = {}
                  this.appLoading = false
                })
              }, 500)
              break
            default:
              break
          }
        }
      })
    },
    canceTopUp() {
      this.openAmount = false
      this.topUpForm = {}
    },
    // 如果用户没有支付，而弹出层被关闭了
    handleClose() {
      this.$confirm('您确定放弃支付吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.msgNoticeError('您已放弃支付，可以回到充值记录查询列表里面再次支付')
        this.openPay = false
        this.topUpForm = {}
        // 关闭轮询
        clearInterval(this.intervalObj)
      }).catch(() => {
        this.msgNoticeSuccess('欢迎继续支付')
      })
    },
    // 客户充值
    handleAlipayTopUp(row) {
      this.topUpForm = {}
      this.openAmount = true
      this.topUpType = 1
      this.topUpForm.topUpMemberId = row.id
    },
    // 级联选择的值
    handleChange(arr) {
      this.form.province = CodeToText[arr[0]]
      this.form.city = CodeToText[arr[1]]
      this.form.county = CodeToText[arr[2]]
      // console.log('selectedOptions', this.selectedOptions)
    },
    sexFormat(row, column) {
      return this.selectDictLabel(this.sexOptions, row.gender)
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status == 0 ? '启用' : '停用'
      this.$confirm('确认要"' + text + '""' + row.realName + '"吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return changeMemberStatus(row.id, row.status)
      }).then(() => {
        this.msgNoticeSuccess(text + '成功')
      }).catch(function() {
        row.status = row.status === 0 ? 1 : 0
      })
    },
    /** 查询轮播图管理列表 */
    getList() {
      this.loading = true
      listMember(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        const { records, total } = response.data
        this.list = records
        this.total = total
        this.loading = false
      })
    },
    // 状态(0.可用 1.不可用)字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        phone: null,
        password: undefined,
        realName: null,
        gender: null,
        province: null,
        city: null,
        county: null,
        address: null,
        status: 0
      }
      this.selectedOptions = []
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    }
    ,
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    }
    ,
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.form.password = this.initPassword
      this.open = true
      this.title = '添加客户'
    }
    ,
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getMember(id).then(response => {
        this.form = response.data
        // console.log(this.selectedOptions)
        const { province, city, county } = response.data
        this.selectedOptions = [TextToCode[province].code, TextToCode[province][city].code, TextToCode[province][city][county].code]
        this.form.password = ''
        this.open = true
        this.title = '修改客户'
      })
    }
    ,
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMember(this.form).then(response => {
              this.msgNoticeSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addMember(this.form).then(response => {
              this.msgNoticeSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    }
    ,
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除客户编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delMember(ids)
      }).then(() => {
        this.getList()
        this.msgNoticeSuccess('删除成功')
      })
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.phone + '"的新密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        resetMemberPwd(row.id, value).then(response => {
          this.msgNoticeSuccess('修改成功，新密码是：' + value)
        })
      }).catch(() => {
      })
    }
  }
}
</script>
<style scoped lang="scss">
.dialog-member ::v-deep .el-cascader.el-cascader--mini {
  width: 230px;
}

.ali-pay {
  font-size: larger;
  font-weight: bolder;

  .ali-pay-item {
    margin-left: 10px;
  }
}

.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
